package com.yfp.device.service.impl;

import com.yfp.device.domain.Machine;
import com.yfp.device.domain.R;
import com.yfp.device.domain.SysUser;
import com.yfp.device.mapper.MachineMapper;
import com.yfp.device.mapper.SysUserMapper;
import com.yfp.device.service.UserService;
import com.yfp.common.redis.service.RedisService;
import com.yfp.common.security.utils.SecurityUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 用户服务
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private RedisService redisService;

    private final SysUserMapper sysUserMapper;

    private final MachineMapper machineMapper;

    @Value("${yd.define.roleKey.common:common}")
    private String commonRoleKey;

    public UserServiceImpl(SysUserMapper sysUserMapper, MachineMapper machineMapper) {
        this.sysUserMapper = sysUserMapper;
        this.machineMapper = machineMapper;
    }

    /**
     * 补货员用户登录
     *
     * @param userName  用户名/手机号
     * @param password  密码
     * @param machineSn 机器编号
     */
    @Override
    public R<?> userLogin(String userName, String password, String machineSn) {
        try {
            // 判断用户是否是该设备的区域、线路、点位负责人
            Machine machine = machineMapper.selectByUserNameAndMachineSn(userName, machineSn);

            // 判断用户是否是该设备的公司普通用户
            SysUser user = sysUserMapper.selectCommonUserByMachineSn(commonRoleKey, machineSn, userName);

            if (machine == null && user == null) {
                log.error("无效用户");
                return R.fail("无效用户");
            }

            SysUser userInfo = sysUserMapper.selectByUserName(userName);
            if (userInfo == null) {
                return R.fail("补货员不存在");
            }
            boolean checkPassword = SecurityUtils.matchesPassword(password, userInfo.getPassword());
            if (!checkPassword) {
                return R.fail("密码校验错误");
            }

            // 存入缓存
            redisService.setCacheObject("device:login:" + machineSn, userName);

            return R.ok();
        } catch (Exception e) {
            log.error("补货员登录失败", e);
            return R.fail("补货员登录失败");
        }
    }
}
